
import { _decorator, Component, Node, instantiate, Vec3, find, AnimationComponent, Prefab, tween } from 'cc';
import { Utils } from '../data/utils';
import { UIManager } from '../ui/UIManager';
import { Monster } from '../game/Monster';
import { MonsterView } from '../game/MonsterView';
import { Constants } from '../data/Constants';
import { CustomEventListener } from '../data/CustomEventListener';
import { BulletView } from '../game/BullerView';
const { ccclass, property } = _decorator;

/**
 * 战斗管理器,用于创建和管理敌人,输赢的判断
 */
@ccclass('BattleManager')
export class BattleManager extends Component {
    @property({
        type: [Node],
        displayOrder: 1,
    })
    enemyPreFabArray: Node[] = [];//包含所有敌人预制体.

    @property({
        type: Node,
        displayOrder: 3
    })
    enemyParent: Node = null!; //所有敌人复制出来的父级


    @property({
        type: AnimationComponent,
        displayOrder: 2,

    })
    camAnimationComp: AnimationComponent = null!;//摄像机身上的动画组件


    @property({
        type: Prefab,
        displayOrder: 4,
    })
    bulletPrefab: Prefab = null! //子弹预制体

    @property({
        type: Node,
        displayOrder: 5,
    })
    bulletParent: Node = null! //所有子弹的父级

    @property({
        type: Node,
        displayOrder: 6,
    })
    gunShootPoint: Node = null! //武器射击口

    //怪物出生点的4个边界
    private _xMin = -10;
    private _xMax = 10;
    private _zMin = -100;
    private _zMax = -50;

    //战斗中, 同屏存在的最大的敌人数量.
    private _maxEnemyNum = 15;
    //复制敌人的间隔.
    private _enemyCreateInterval = 0.2;
    //当前已经激活的所有敌人
    private _allEnemiesArray: Monster[] = []

    //游戏是否开始
    public _isGameStart: boolean = false;

    static _instance: BattleManager = null!;
    public static instance() {
        return this._instance;
    }

    onLoad() {
        BattleManager._instance = this
    }
    start() {
        this.init()
    }

    //初始化函数,用于游戏开始前的初始化工作,比如怪物的生成
    public init() {
        //打开主界面
        UIManager.showDialog(Constants.UIPage.mainPanel, null!)
        //复制敌人到上限
        this._createEnemy()
        this._isGameStart = false;
    }

    //一般战斗开始前调用,初始化战斗开始后用的变量
    public startGame() {
        this._isGameStart = true;
        CustomEventListener.dispatchEvent(Constants.EventName.MONSTER_MOVE)
    }

    //控制敌人的复制.
    private _createEnemy() {
        //复制敌人有上限,如果已达到或超过上限,则不复制
        if (this._allEnemiesArray && this._allEnemiesArray.length >= this._maxEnemyNum) {
            return;
        }
        this._createASigleEnemy()
        //间隔一段时间,再复制下一个敌人
        this.scheduleOnce(this._createEnemy.bind(this), this._enemyCreateInterval)
    }

    //此函数用于复制一个敌人.
    private _createASigleEnemy() {
        //所有怪物都同几率被复制.先取出数组中一个随机元素的下标.
        const randomIndex = Math.floor(Math.random() * this.enemyPreFabArray.length);
        //根据下标,取出要被复制的随机的怪物的预制体
        const randomEnemyPre = this.enemyPreFabArray[randomIndex];
        //使用instantiate函数,复制一个敌人
        const newEnemy = instantiate(randomEnemyPre)
        //激活
        newEnemy.active = true
        //将复制出来的怪物设置到统一的父级下面,作为子物体
        newEnemy.setParent(this.enemyParent);

        //获得敌人身上的MonsterView组件.
        let view = newEnemy.getComponent(MonsterView);
        if (!view) {
            view = newEnemy.addComponent(MonsterView);
        }

        //生成一个新的怪物控制程序
        const mons = new Monster()
        mons.init(view)
        this._allEnemiesArray.push(mons)

        let randomX = Utils.getRandomValueInRange(this._xMin, this._xMax)
        let randomY = newEnemy.position.y
        let randomZ = Utils.getRandomValueInRange(this._zMin, this._zMax)

        //将怪物放置在随机的坐标点 飞行类 y轴为1
        if (view.isFlyMonster) {
            newEnemy.setPosition(new Vec3(randomX, randomY + 1, randomZ))

        } else {
            newEnemy.setPosition(new Vec3(randomX, randomY, randomZ))
        }
    }

    //开火 pos:子弹射向的目标点
    public fire(pos: Vec3) {
        //游戏是否开始
        if (!this._isGameStart) {
            return
        }
        //复制子弹
        const bullet = instantiate(this.bulletPrefab) as Node;
        bullet.setParent(this.bulletParent)
        //子弹的初始坐标, 枪口坐标
        bullet.setPosition(this.gunShootPoint.worldPosition)
        //让子弹的方向等于开火点物体的方向 --四元素
        bullet.setWorldRotation(this.gunShootPoint.worldRotation)

        let view = bullet.getComponent(BulletView)
        if (!view) {
            view = bullet.addComponent(BulletView)
        }
        view.init(pos)

        // //向pos对应的目标点飞去.
        // tween(bullet)
        //     .to(1, { position: pos })
        //     .call(() => {
        //         bullet.destroy()
        //     })
        //     .start();
    }

    //游戏失败
    public playerDead() {
        console.log('this._isGameStart', this._isGameStart)
        if (this._isGameStart) {
            this._isGameStart = false;
            //让所有怪物立刻停止前进
            this._allEnemiesArray.map(item => {
                item.stopMove();
            })
        }
        //打开失败界面FailPanel
        UIManager.hideDialog(Constants.UIPage.gamePanel, null!)
        UIManager.showDialog(Constants.UIPage.failPanel, null!)
    }


    //怪物死亡
    public monsterDead(mons: Monster) {

        this._allEnemiesArray.map((item, index) => {
            if (item == mons) {
                this._allEnemiesArray.splice(index, 1)
                if (this._allEnemiesArray.length == 0) {
                    //游戏胜利
                    UIManager.hideDialog(Constants.UIPage.gamePanel);
                    UIManager.showDialog(Constants.UIPage.winPanel, null!);
                }
                return;
            }
        })
    }

    //回收所有怪物
    public recycleMonsters() {
        this._allEnemiesArray.map(item => {
            item.dispose()
        })
        this._allEnemiesArray = []
    }

}

